//package com.gitee.mazhenggg.demo.gateway.filter;
//
//import io.opentelemetry.api.OpenTelemetry;
//import io.opentelemetry.api.trace.Span;
//import io.opentelemetry.api.trace.SpanKind;
//import io.opentelemetry.api.trace.Tracer;
//import io.opentelemetry.context.Scope;
//import io.opentelemetry.semconv.trace.attributes.SemanticAttributes;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.http.server.reactive.ServerHttpRequest;
//import org.springframework.http.server.reactive.ServerHttpResponse;
//import org.springframework.web.server.ServerWebExchange;
//import org.springframework.web.server.WebFilter;
//import org.springframework.web.server.WebFilterChain;
//import reactor.core.publisher.Mono;
//
//public class WebTraceFilter implements WebFilter {
//    @Autowired
//    private OpenTelemetry openTelemetry;
//
//    @Value("${spring.application.name}")
//    private String applicationName;
//
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain webFilterChain) {
//        ServerHttpRequest request = exchange.getRequest();
//        ServerHttpResponse response =exchange.getResponse();
//        Span span = getServerSpan(openTelemetry.getTracer(applicationName), request);
//        Scope scope = span.makeCurrent();
//        String traceId = span.getSpanContext().getTraceId();
//        response.getHeaders().add("traceId",traceId );
//        ServerHttpRequest traceRequest = request.mutate().header("traceId", traceId).build();
//
//        //ServerHttpResponse traceResponse = response.mutate().header("traceId", traceId).build();
//        exchange = exchange.mutate().request(traceRequest).build();
//        span.setAttribute("params", request.getQueryParams().toString());
//
//        return webFilterChain.filter(exchange)
//                .doFinally((signalType) -> {
//                    scope.close();
//                    span.end();
//                })
//                .doOnError(span::recordException);
//    }
//
//    private Span getServerSpan(Tracer tracer, ServerHttpRequest serverHttpRequest) {
//        return tracer.spanBuilder(serverHttpRequest.getPath().toString()).setNoParent().setSpanKind(SpanKind.SERVER).setAttribute(SemanticAttributes.HTTP_METHOD, serverHttpRequest.getMethod().name()).startSpan();
//    }
//}
